package com.hlk.interceptors;

import com.hlk.enums.ResponseStatusEnum;
import com.hlk.enums.UserStatusEnum;
import com.hlk.exception.HuaException;
import com.hlk.pojo.AppUser;
import com.hlk.utils.JsonUtils;
import com.hlk.utils.redis.RedisKeys;
import com.hlk.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hlk
 * @version 1.0
 * @date 2020-12-17 11:32
 */
@Component
public class UserActiveInterceptor extends BaseInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("headerUserId");
        String userInfoStr = redisUtils.get(RedisKeys.getUserInfoKey(userId));
        AppUser user = null;
        if (StringUtils.isNotBlank(userInfoStr)) {
            user = JsonUtils.jsonToPojo(userInfoStr, AppUser.class);
        } else {
            throw new HuaException(ResponseStatusEnum.UN_LOGIN);
        }

        // 用户被冻结
        if (user.getActiveStatus() == null || user.getActiveStatus().equals(UserStatusEnum.FROZEN)) {
            throw new HuaException(ResponseStatusEnum.USER_FROZEN);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
